//
//  ZYCProtalSendNoticeViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/2.
//

#import "ZYCProtalSendNoticeViewController.h"
#import "ZYCProtalNoticeView.h"
#import <TZImagePickerController.h>
#import "ZYCProtalNoticePushPeopleViewController.h"
#import "UIApplication+Visible.h"
#import "ZYCNavigationController.h"
#import "ZYCNoticePushView.h"
#import "ZYCRoleTreeModel.h"
#import "ZYCUserRoleModel.h"

@interface ZYCProtalSendNoticeViewController ()<UINavigationControllerDelegate,ZYCProtalNoticeViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) ZYCProtalNoticeView *publishNoticeView;
@property (nonatomic, strong) NSMutableArray * selectedPhotos;
@property (nonatomic, strong) NSMutableArray * selectedAssets;
@property (nonatomic, assign) NSUInteger updateImageCount;
@property (nonatomic, strong) NSMutableArray *updateImageResults;
@property (nonatomic, strong) NSMutableArray *sendUserList;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, copy) NSString *content;


@end

@implementation ZYCProtalSendNoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.delegate = self;
    [self.view addSubview:self.publishNoticeView];

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documentPath stringByAppendingPathComponent:@"tree.data"];;
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (array > 0) {
        _dataSource = array.mutableCopy;
    }else{
        _dataSource =[NSMutableArray arrayWithCapacity:0];
        [self loadTeacherTree];
    }


}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}






#pragma mark - UINavigationControllerDelegate
//-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
//    [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:[self class]] animated:YES];
//}

// 教师树
- (void)loadTeacherTree{
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] getUrlString:Common_Get_QueryTearcher requestService:RequestServiceSystem parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                ZYCRoleTreeModel *model =  [ZYCRoleTreeModel yy_modelWithDictionary:[responseObject[@"body"] lastObject]];
                for (ZYCRoleTreeModel  *m1 in model.children) {
                    m1.father = model;
                    for (ZYCRoleTreeModel *m2 in m1.children) {
                        m2.father = m1;
                        for (ZYCRoleTreeModel *m3 in m2.children) {
                            m3.father = m2;
                            for (ZYCRoleTreeModel *m4 in m3.children) {
                                m4.father = m3;
                                for (ZYCRoleTreeModel *m5 in m4.children) {
                                    m5.father = m4;
                                    for (ZYCRoleTreeModel *m6 in m5.children) {
                                        m6.father = m5;
                                    }
                                }
                            }
                        }
                    }
                }
                
                [self.dataSource addObject:model];
                [self loadParentTree];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {

        }];
}

//家长树
- (void)loadParentTree{
    [[URLManager sharedURLManager] getUrlString:Common_Get_QueryParent requestService:RequestServiceSystem parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                ZYCRoleTreeModel *model =  [ZYCRoleTreeModel yy_modelWithDictionary:[responseObject[@"body"] lastObject]];
                for (ZYCRoleTreeModel  *m1 in model.children) {
                    m1.father = model;
                    for (ZYCRoleTreeModel *m2 in m1.children) {
                        m2.father = m1;
                        for (ZYCRoleTreeModel *m3 in m2.children) {
                            m3.father = m2;
                            for (ZYCRoleTreeModel *m4 in m3.children) {
                                m4.father = m3;
                            }
                        }
                    }
                }

                [self.dataSource addObject:model];
       
                 NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
                 NSString *path = [documentPath stringByAppendingPathComponent:@"tree.data"];
                 [NSKeyedArchiver archiveRootObject:self.dataSource toFile:path];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}



- (void)uploadWithImage:(UIImage *)image{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.updateImageCount --;
                NSString *filePath = responseObject[@"body"][@"url"];
                [self.updateImageResults addObject:filePath];
                [self publishNotice];
            }else{
                [MrjToast makeToast:@"图片上传失败" makeView:self.view];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
}


// 发布通知
- (void)clickPublishNotice{
    
    self.updateImageCount = 0;
    self.updateImageResults = [NSMutableArray arrayWithCapacity:0];
    
    if (self.publishNoticeView.selectedPhotos.count > 0) {
        for (UIImage *image in self.publishNoticeView.selectedPhotos) {
            self.updateImageCount ++;
            [self uploadWithImage:image];
        }
    }else{
        [self publishNotice];
    }
}


- (void)publishNotice{
    if (self.updateImageCount != 0) {// 防止发布多条
        return;
    }
    
    if (self.updateImageResults.count > 0) {
        NSMutableString *stringM = [NSMutableString string];
        for (NSString *filePath in self.updateImageResults) {
            NSString *fullUrlString =  [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],filePath];
        [stringM appendString:[NSString stringWithFormat:@"<img class=\"wscnph\"src =%@>",fullUrlString]];
        };
        if (self.publishNoticeView.content.length > 0) {
            self.content = [NSString stringWithFormat:@"<p>%@%@</p>",self.publishNoticeView.content,stringM];
        }else{
            self.content = [NSString stringWithFormat:@"<p>%@</p>",stringM];
        }

    }else{
        self.content = [NSString stringWithFormat:@"<p>%@</p>",self.publishNoticeView.content];
    }
    
    if (self.publishNoticeView.title.length == 0) {
        [MrjToast makeToast:@"请输入标题" makeView:self.view];
        return;
    }
    
    if (self.publishNoticeView.content.length == 0 && self.publishNoticeView.selectedPhotos.count == 0) {
        [MrjToast makeToast:@"请输入内容" makeView:self.view];
        return;
    }

    if (self.sendUserList.count == 0) {
        [MrjToast makeToast:@"请选择推送人" makeView:self.view];
        return;
    }
    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"2" forKey:@"noticeType"];
    [params setObject:self.publishNoticeView.title forKey:@"title"];
    [params setObject:self.content forKey:@"content"];
    [params setObject:self.sendUserList forKey:@"sendUserList"];

    [MrjSVProgressHUD showWithStatus:@"发布中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_PublishNotice requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"message"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                });
            }

        } failure:^(NSError * _Nonnull error) {
            [MrjSVProgressHUD dismiss];
        }];
}


// 递归思想
- (NSArray *)filterSource:(NSArray *)sourceArray type:(NSString *)type{
    if (sourceArray.count == 0)  return nil;
    NSMutableArray *mArr = [NSMutableArray arrayWithCapacity:0];
    for (ZYCRoleTreeModel *model in sourceArray) {
        if ([model.dateType isEqualToString:type]) {
            [mArr addObject:model];
        }
        NSArray *temp = [self filterSource:model.children type:type];
        if (temp.count > 0) {
            [mArr addObjectsFromArray:temp];
        }
    }
    return mArr.copy;
}

#pragma mark - ZYCProtalNoticeViewDelegate
// 发布
- (void)protalNoticeViewDidClickComfirm{
    [self clickPublishNotice];
    
}
//取消
- (void)protalNoticeViewDidClickCancel{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)protalNoticeViewDidClickAddPhoto{
    [self presentFliter];
}

- (void)presentFliter{
    ZYCWeakSelf
    UIAlertController *alert = [[UIAlertController alloc] init];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //判断权限
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            [alertC addAction:action1];
            [alertC addAction:action2];
            [self presentViewController:alertC animated:YES completion:nil];
        }else {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushTZImagePickerViewController];

    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:photoAction];
    [alert addAction:albumAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)pushTZImagePickerViewController{
    ZYCWeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    if (self.publishNoticeView.selectedAssets.count > 0) {
        imagePickerVc.selectedAssets = self.publishNoticeView.selectedAssets;
    }
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.publishNoticeView.selectedAssets = [NSMutableArray arrayWithArray:assets];
        weakSelf.publishNoticeView.selectedPhotos = [NSMutableArray arrayWithArray:photos];
    }];
     imagePickerVc.barItemTextColor = [UIColor blackColor];
     [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    imagePickerVc.allowPickingVideo = NO;
     imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
     imagePickerVc.naviBgColor = [UIColor whiteColor];
     imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
            [self.selectedAssets addObject:asset];
            [self.selectedPhotos addObject:image];
            self.publishNoticeView.selectedAssets = self.selectedAssets;
            self.publishNoticeView.selectedPhotos = self.selectedPhotos;
        }];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}



// 选择推送人
- (void)protalNoticeViewDidClickPushRange{
    ZYCWeakSelf
    ZYCProtalNoticePushPeopleViewController *vc = [[ZYCProtalNoticePushPeopleViewController alloc] init];
    vc.titleString = @"推送范围";
    vc.dataSource = self.dataSource;
    vc.selectBlock = ^(NSMutableArray * _Nonnull selectArr) {
        weakSelf.sendUserList = selectArr;
        weakSelf.publishNoticeView.pushRangeView.total = selectArr.count;
    };
    [self.navigationController pushViewController:vc animated:YES];

}



#pragma mark - getters



- (ZYCProtalNoticeView *)publishNoticeView {
    if (!_publishNoticeView) {
        _publishNoticeView = [[ZYCProtalNoticeView alloc] initWithFrame:self.view.bounds];
        _publishNoticeView.delegate = self;
    }
    return _publishNoticeView;
}


- (NSMutableArray *)selectedPhotos {
    if (!_selectedPhotos) {
        _selectedPhotos = [[NSMutableArray alloc] init];
    }
    return _selectedPhotos;
}

- (NSMutableArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [[NSMutableArray alloc] init];
    }
    return _selectedAssets;
}


- (NSMutableArray *)sendUserList {
    if (!_sendUserList) {
        _sendUserList = [[NSMutableArray alloc] init];
    }
    return _sendUserList;
}

-(void)dealloc{
    self.publishNoticeView = nil;
    self.navigationController.delegate = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
